/*
 * Copyright 2007 Xplayat, S.L. All rights reserved.
 * Propiedad de Xplayat. 
 */
package es.xpt.ysf.view.menu;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import es.xpt.ysf.YSFException;
import es.xpt.ysf.view.menu.model.MenuBean;
import es.xpt.ysf.view.menu.model.Menus;

public class MenuFactory {
	public static Map<String, MenuBean> createMenu(String menuURL) throws YSFException {

		StringTokenizer tokenizer = new StringTokenizer(menuURL, ",");
		Map<String, MenuBean> hash = new HashMap<String, MenuBean>();
		try {
			JAXBContext jaxbContextResponse = JAXBContext.newInstance("es.xpt.ysf.view.menu.model");
			Unmarshaller unmarshaller = jaxbContextResponse.createUnmarshaller();
	
			while (tokenizer.hasMoreTokens()) {
				String menu = tokenizer.nextToken().trim();
				if (menu.startsWith("xml://")) {
					InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("/" + menu.substring(6));
					List<MenuBean> list = ((Menus) unmarshaller.unmarshal(is)).getMenu();
					for (MenuBean m : list) {
						hash.put(m.getModule(), m);
					}
				} else {
					throw new YSFException("No supported protocol");
				}
			}
		} catch (JAXBException e) {
			throw new YSFException(e);
		}
		return hash;
	}
}
